package com.lantosec.hmrp.modules.workflow.service.impl;

import com.alibaba.fastjson.JSON;
import com.lantosec.hmrp.modules.sysdata.entity.SysProcessForm;
import com.lantosec.hmrp.modules.sysdata.service.ISysProcessFormService;
import com.lantosec.hmrp.modules.workflow.service.IWorkflowBusinessService;
import com.lantosec.hmrp.modules.workflow.service.IWorkflowDeployService;
import com.lantosec.hmrp.modules.workflow.service.IWorkflowRepositoryService;
import com.lantosec.hmrp.modules.workflow.service.IWorkflowRuntimeService;
import com.lantosec.hmrp.modules.workflow.vo.FlowProcdefVO;
import com.lantosec.hmrp.modules.workflow.vo.SaveProcessTaskVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 工作流业务服务接口
 *
 * @author lichaowei
 * @date 2020/5/8
 */
@Service
@Primary
@Log4j2
public class WorkflowBusinessServiceImpl implements IWorkflowBusinessService {

    @Autowired
    IWorkflowRepositoryService workflowRepositoryService;

    @Autowired
    IWorkflowDeployService workflowDeployService;

    @Autowired
    IWorkflowRuntimeService workflowRuntimeService;

    @Autowired
    ISysProcessFormService sysProcessFormService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean startProcess(String userId, String definitionKey, Object formData) {
        // 根据流程KEY查询工作流的最新的流程定义ID
        FlowProcdefVO flowProcdefVO = workflowRepositoryService.getProcessDefinitionByKey(definitionKey);
        if (Objects.isNull(flowProcdefVO)) {
            return false;
        }
        String definitionId = flowProcdefVO.getId();

        // 查询工作流对应的数据表单信息
        SysProcessForm sysProcessForm = sysProcessFormService.selectByDefinitionId(definitionId);
        if (Objects.isNull(sysProcessForm)) {
            return false;
        }
        // 表单数据
        /*FormDataVO formDataVO = new FormDataVO();
        formDataVO.setMaster(formData);
        List<FormChildDataVO> childDataVOList = new ArrayList<>();
        // TODO 多子表对象怎么做到子表与数据的对应关系
        formDataVO.setChildren(childDataVOList);*/
        String formDataJson = JSON.toJSONString(formData);

        // 组织参数
        SaveProcessTaskVO saveVO = new SaveProcessTaskVO();
        saveVO.setUserId(userId);
        saveVO.setProcdefId(sysProcessForm.getProcdefId());
        saveVO.setLayoutId(sysProcessForm.getStartLayoutId());
        saveVO.setFormTableId(sysProcessForm.getFormTableId());
        saveVO.setFormData(formDataJson);

        // 启动流程
        workflowRuntimeService.save(saveVO);

        return true;
    }

}
